package org.qiyu.live.im.core.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.Resource;
import org.qiyu.live.im.core.server.common.ChannelHandlerContextCache;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.handler.impl.ImHandlerFactoryImpl;
import org.springframework.stereotype.Component;

/**
 *  im消息处理器
 * 作者：無言
 * 时间：2024/12/2 21:21
 * 描述：永无BUG
 */

@Component
public class ImServerCoreHandler extends SimpleChannelInboundHandler {


    @Resource
    private  ImHandlerFactory imHandlerFactory;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if(!(msg instanceof ImMsg)) {
            throw new IllegalArgumentException("error msg type, msg is " + msg);
        }
        ImMsg imMsg = (ImMsg) msg;

        //根据消息类型使用不同的消息处理器处理消息，这里使用 工厂模式 + 策略模式实现代码的抽取
        imHandlerFactory.doMsgHandler(channelHandlerContext, imMsg);

    }

    /**
     * 用户正常断线或者异常断线情况，都会被这个方法监听到
     * 可以通过channelHandlerContext 拿到用户id, 登陆时已经通过attr方法绑定
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接，移除缓存
        Long userId = ImContextUtils.getUserId(ctx);

    }


}
